const path = require('path');
//每次build时清空dist文件夹
const {CleanWebpackPlugin} = require('clean-webpack-plugin');
//设置不生成txt
const TerserPlugin = require("terser-webpack-plugin");
//css独立打包
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
//对HTML的处理
const HtmlWebpackPlugin = require('html-webpack-plugin');

const webpack = require('webpack');

let getHtmlConfig = function(name){
  return {
    template: './src/view/' + name + '.html',
    filename: 'view/' + name + '.html',
    inject : true,
    hash: true,
    chunks: ['common', name],
    minify: {
      collapseWhitespace: false
    }
  }
}

module.exports = {
  entry: {
    'common': './src/page/common/index.js',
    'index': './src/page/index/index.js',
    'login': './src/page/login/index.js',
    'catalog-main': './src/page/catalog-main/index.js',
  },
  output: {
    //打包之后的文件名
    filename: 'js/[name].js',
    //打包之后的路径
    path: path.resolve(__dirname, 'dist'),
  },
  plugins: [
    //清空dist
    //new CleanWebpackPlugin(),
    //new插件，让css独立打包
    new MiniCssExtractPlugin({
      filename: 'css/[name].css',
    }),
    //对HTML的处理
    new HtmlWebpackPlugin(getHtmlConfig('index')),
    new HtmlWebpackPlugin(getHtmlConfig('catalog-main')),
    new HtmlWebpackPlugin(getHtmlConfig('login')),
    new webpack.HotModuleReplacementPlugin()
  ],
  devServer: {
    port: 8888,
    static: {
      directory: path.resolve(__dirname, 'dist'),
    }
  },
  module: {
    rules: [
      {
        test: /\.css$/,
        use: [
          {
            loader: MiniCssExtractPlugin.loader,
            options: {
              publicPath: '../'
            }
          },
          'css-loader'
        ],
      },
      {
        test: /\.(png|svg|jpg|gif)$/,
        use:[
          {
            loader: 'url-loader',
            options: {
              limit: 8,
              name: 'images/[name].[ext]',
              esModule: false,
            }
          }
        ],
        type: 'javascript/auto'
      },
      {
        test : /\.htm$/,
        use : {
          loader: 'html-loader',
          options: {
            esModule: false,
            minimize: false
          }
        }
      }
    ],
  },
  optimization: {
    //是否压缩
    minimize: false,
    minimizer: [
      new TerserPlugin({
        extractComments: false,//不将注释提取到单独的文件中
      }),
    ],
    splitChunks:{
      cacheGroups: {
        commons: {
          name: 'util',
          chunks: 'all',
          minChunks: 2,
          minSize: 0
        },
      }
    }
  },
  //将已经引用过的js保存，作为外部变量
  externals: {
    'jquery': 'window.jQuery'
  },
  //定义别名
  resolve: {
    alias: {
      util: __dirname + '/src/util',
      page: __dirname + '/src/page',
      images: __dirname + '/src/images',
      service: __dirname + '/src/service',
      node_modules: __dirname + '/node_modules',
    }
  },
  mode: 'development'
};